'use strict'

const Controller = require('egg').Controller
const jwt = require('jsonwebtoken')

class UserController extends Controller {
	// mysql this.app.mysql 第三方的egg插件 而且注册在plugin下吗
	// crp   this.ctx.helper
	async login() {
		const { ctx, app } = this

		// 1. 接收参数
		const { username, password } = ctx.request.body
		// 2. 基于参数处理 数据
		// 2.1. 查询用户是否存在，如果不存在，让用户注册
		const queryInfo = await app.mysql.query(
			`select * from users where username=?`,
			[username]
		)
		if (queryInfo.length !== 0) {
			// 2.2 登陆
			const data = await app.mysql.query(
				`select * from users where username=? and password=?`,
				[username, ctx.helper.getPassword(password)]
			)
			console.log('data:', data)
			if (data.length) {
				// 2.3 token
				const token = jwt.sign(
					{ id: data[0].id, username: data[0].username },
					'1904',
					{ expiresIn: '24h' }
				)
				ctx.body = { code: 0, msg: 'success', data: { token } }
			} else {
				ctx.body = { code: -1, msg: 'fail' }
			}
		} else {
			ctx.body = { code: 0, msg: '请注册' }
		}
	}

	async register() {
		const { ctx, app } = this
		// 1. 接收参数
		const { username, password, avatar, nickname = '' } = ctx.request.body
		// 2. 处理根据exec
		const insertData = await app.mysql.query(
			`insert into users (username, password,avatar,nickname) values (?,?,?,?)`,
			[username, ctx.helper.getPassword(password), avatar, nickname]
		)
		if (insertData.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '注册成功',
				data: { insertId: insertData.insertId }
			}
		} else {
			ctx.body = {
				code: -1,
				msg: '注册失败'
			}
		}
	}

	async users() {
		const { ctx, app } = this
		// 接收权限id
		// const { id } = ctx.state.userInfo
		// 1. 接收参数
		// console.log('id,', id)
		const { page = 1, size = 5 } = ctx.query
		// 2. 处理参数 排序 order by id desc 倒序
		const list = await app.mysql.query(`select * from users limit ? offset ?`, [
			size * 1,
			(page - 1) * size
		])
		ctx.body = {
			code: 0,
			msg: '查询成功',
			data: { list }
		}
	}

	async list() {
		// this.ctx.helper 挂载工具函数
		// const data = await this.app.mysql.query(`select * from blogs`)
		const password = this.ctx.helper.getPassword('123')
		console.log(this.ctx.request.body, '--------')
		this.ctx.body = {
			code: 0,
			msg: 'success',
			data: { password, list: this.ctx.request.body }
		}
	}
	async post() {
		const password = this.ctx.helper.getPassword('123')
		this.ctx.body = {
			code: 0,
			msg: 'success',
			data: { password }
		}
	}
}

module.exports = UserController
